package com.blog.utils;

import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

/**
 * Request
 * 
 * @author ZhangBo
 * 
 */
public class RequestUtil {

	/**
	 * 设置Request属性对象值
	 * 
	 * @param name
	 * @param val
	 */
	public static void setAttribute(String name, Object val) {
		ServletActionContext.getRequest().setAttribute(name, val);
	}

	/**
	 * 获取Request属性对象值
	 * 
	 * @param name
	 * @return
	 */
	public static Object getAttribute(String name) {
		HttpServletRequest request = ServletActionContext.getRequest();
		return request.getAttribute(name);
	}

	/**
	 * 获取提交的参数
	 * 
	 * @param name
	 * @return
	 */
	public static String getParameter(String name) {
		HttpServletRequest request = ServletActionContext.getRequest();
		return request.getParameter(name);
	}

	public static void setCharacterEncoding(String env)
			throws UnsupportedEncodingException {
		HttpServletRequest request = ServletActionContext.getRequest();
		request.setCharacterEncoding(env);
	}

	/**
	 * 获取用户实际IP地址
	 * 
	 * @return
	 */
	public static String getRemortIP() {
		HttpServletRequest request = ServletActionContext.getRequest();
		if (request.getHeader("x-forwarded-for") == null) {
			return request.getRemoteAddr();
		}
		return request.getHeader("x-forwarded-for");
	}

	/**
	 * 获取用户实际IP地址
	 * 
	 * @param request
	 * @return
	 */
	public static String getRemortIP(HttpServletRequest request) {
		if (request.getHeader("x-forwarded-for") == null) {
			return request.getRemoteAddr();
		}
		return request.getHeader("x-forwarded-for");
	}

	/**
	 * 获取用户实际IP地址
	 * 
	 * @return
	 */
	public static String getIpAddr() {
		HttpServletRequest request = ServletActionContext.getRequest();
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}

	/**
	 * 获取用户实际IP地址
	 * 
	 * @param request
	 * @return
	 */
	public static String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}
}
